<template>
  <div class="loginWrap">
    <!-- 头部 -->
    <app-headers></app-headers>
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <div class="contentbox">
        <van-field
          v-model="username"
          name="username"
          label="用户名："
          placeholder="请输入6~18位数字或字母。"
          :rules="[
            {
              required: true,
              message: '请填写用户名',
              validator: checkname,
              trigger: 'onChange'
            }
          ]"
        />
        <van-field
          :disabled="$data.nameIslock == true ? false : true"
          class="password"
          v-model="password"
          :type="type"
          name="password"
          label="密码："
          placeholder="请输入6~16位数字或字母"
          :rules="[
            {
              validator: pswReg,
              required: false,
              message: '请填写密码',
              trigger: 'onChange'
            }
          ]"
        />
        <span class="showhide-icon">
          <b :class="showhide" @click="pswChange"></b>
        </span>
        <van-field
          :disabled="$data.pswIslock == true ? false : true"
          class="code"
          v-model="code"
          type="text"
          name="identifyCode"
          placeholder="请输入验证码"
          :rules="[
            {
              required: false,
              message: '请填写验证码',
              validator: cheeckCord,
              trigger: 'onChange'
            }
          ]"
        />
        <span class="getcode" @click="testCode(4)">
          <app-sidentify :identifyCode="identifyCode"></app-sidentify>
        </span>
      </div>
      <!-- 下半部分 -->
      <div class="bottombox">
        <span class="msgreply"> {{ msgreply }}</span>
        <div class="info">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            :disabled="
              $data.nameIslock == true &&
              $data.pswIslock == true &&
              $data.codeIslock == true
                ? false
                : true
            "
            >注册</van-button
          >
        </div>
        <van-row type="flex">
          <van-col span="24" style="font-size:13px; margin-bottom:15px">
            *点击注册代表同意
            <router-link to="###">《好乐买软件隐私声明》</router-link>
          </van-col>
        </van-row>
        <!-- 右对齐 -->
        <van-row type="flex" justify="end">
          <van-col span="8">
            <router-link to="/login">已有账号，去登录</router-link>
          </van-col>
        </van-row>
      </div>
    </van-form>
  </div>
</template>

<script>
import appHeaders from "../components/headers";
import appSidentify from "../components/identifyCode";
import usersApi from "../api/userApi";
export default {
  data() {
    return {
      username: "",
      password: "",
      code: "", //输入的验证码
      identifyCode: "", //图片验证码
      msgreply: "", //正则提示信息
      type: "password", //默认password
      showhide: "hide", //密码图片默认隐藏
      nameIslock: false, //用户名锁
      pswIslock: false, //密码锁
      codeIslock: false //验证码锁
    };
  },
  methods: {
    //提交表单 注册功能
    onSubmit(values) {
      // 发完请求，全部重新上锁
      this.nameIslock = false;
      this.pswIslock = false;
      this.codeIslock = false;
      // // 发完请求，重新换验证码
      this.testCode(4);
      // 使用md5加密密码
      let encryptPassword = this.$md5(values.password);
      usersApi
        .reg(values.username, encryptPassword)
        .then(res => {
          if (res.data.code) {
            this.mounted(res.data.message);
            this.$router.push({
              path: "/login",
              query: { username: values.username }
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 轻提示，显示注册成功
    mounted(val) {
      this.$toast(val);
    },

    // 生成验证码
    testCode(n) {
      var arr = [];
      for (var i = 0; i < n; i++) {
        var num = parseInt(Math.random() * 10);
        if (num >= 0 && num <= 9) {
          arr.push(num);
        }
        // else if ((num >= 97 && num <= 122) || (num >= 65 && num <= 90)) {
        //   arr.push(String.fromCharCode(num));
        // }
        else {
          i--;
        }
      }
      return (this.identifyCode = arr.join(""));
    },

    // 验证用户名
    checkname(val) {
      new Promise(resolve => {
        return resolve(/^[0-9a-zA-Z_]{6,18}$/.test(val));
      }).then(res => {
        if (res) {
          // 正则通过，发请求
          this.msgreply = "";
          usersApi.checkname(this.username).then(res => {
            if (!res.data.code) {
              // 账号已存在，code=0，不允许注册
              this.msgreply = "该用户名太热门了，请换一个吧。";
              this.nameIslock = false;
            } else {
              this.nameIslock = true;
            }
          });
        } else {
          // 正则不通过
          if (val.length > 18) {
            this.msgreply = "用户名位数太多了,太多了啊。";
          } else {
            this.msgreply = "请输入6~18位数字或字母。";
          }
          this.password = "";
          this.nameIslock = false;
        }
      });
    },

    // 密码可见与否
    pswChange() {
      if (this.showhide == "hide") {
        this.type = "text";
        this.showhide = "show";
      } else {
        this.type = "password";
        this.showhide = "hide";
      }
    },

    // 验证密码正则
    pswReg(val) {
      new Promise(resolve => {
        return resolve(/^[0-9a-zA-Z_]{6,16}$/.test(val));
      }).then(res => {
        if (res) {
          // 正则通过，
          this.msgreply = "";
          this.pswIslock = true;
        } else {
          // 正则不通过
          if (val.length > 16) {
            this.msgreply = "密码位数太多了,太多了啊。";
          } else {
            this.msgreply = "密码设置太简单了，请输入6~18位数字或字母。";
          }
          this.pswIslock = false;
          this.code = "";
        }
      });
    },

    // 验证验证码
    cheeckCord() {
      if (this.code.length >= 4) {
        if (this.code.toLowerCase() !== this.identifyCode.toLowerCase()) {
          this.msgreply = "请输入正确的验证码。";
          this.codeIslock = false;
        } else {
          this.msgreply = "";
          this.codeIslock = true;
        }
      } else {
        this.msgreply = "";
        this.codeIslock = false;
      }
    }

    //
  },

  created() {
    // 页面刷新获取验证码
    this.testCode(4);
  },

  components: {
    appHeaders,
    appSidentify
  }
};
</script>

<style scoped lang='scss'>
@import "@/assets/sass/common.scss";
@import "@/assets/sass/vw.scss";

.van-form {
  width: 100%;
  height: v(607);
  padding-top: v(10);
  background-color: #eee;
  .contentbox {
    padding: 0 v(20);
    position: relative;
    background: white;
    .van-field {
      height: v(45);
      font-size: v(16);
      line-height: v(45);
    }
    .password {
      width: v(305);
    }
    .code {
      width: v(250);
    }
    .showhide-icon {
      display: block;
      position: absolute;
      top: v(45);
      right: 0;
      width: v(50);
      height: v(45);
      background-color: #fff;
      z-index: 3;
      .hide {
        display: block;
        margin: v(13.5) 0 0 v(16);
        width: v(18);
        height: v(18);
        background: url("/img/elf_pic.png") v(-170) v(-0) no-repeat;
        background-size: v(250) v(250);
      }
      .show {
        display: block;
        margin: v(13.5) 0 0 v(16);
        width: v(18);
        height: v(18);
        background: url("/img/elf_pic.png") v(-170) v(-23) no-repeat;
        background-size: v(250) v(250);
      }
    }
    .getcode {
      display: block;
      position: absolute;
      top: v(96);
      right: v(10);
      width: v(103);
      height: v(45);
      // background-color: #58bc58;
      z-index: 3;
    }
  }

  .bottombox {
    padding: 0 vw(20);
    font-size: v(14);
    color: #444;
    line-height: v(20);
    .msgreply {
      display: block;
      line-height: v(30);
      margin-bottom: v(10);
      color: #ef3d2d;
      font-size: v(14);
    }
    .info {
      margin: 0 v(10);
      height: v(50);
      .van-button {
        margin-top: v(15);
        background: #d70057;
        height: v(35);
      }
    }
  }
}
</style>